package com.jiazhong.example.project.bookstore.front.listener;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jiazhong.example.project.bookstore.commons.bean.OrderItem;
import com.jiazhong.example.project.bookstore.commons.bean.RocketMQOrder;
import com.jiazhong.example.project.bookstore.commons.bean.Stock;
import com.jiazhong.example.project.bookstore.front.service.StockService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@Component
//@RocketMQTransactionListener(txProducerGroup = "order01")
public class StockIsSufficientListener implements RocketMQLocalTransactionListener {
    @Resource
    private StockService stockService;
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Transactional(rollbackFor = Exception.class)
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        log.info("开始校验图书库存是否充足");
        Object payload = message.getPayload();
        String body = new String((byte[]) payload, StandardCharsets.UTF_8);
        RocketMQOrder rocketMQOrder = JSONArray.parseObject(body, RocketMQOrder.class);
        log.info("获取到的信息是：{}", rocketMQOrder);
        List<OrderItem> orderItemList = rocketMQOrder.getOrderItemList();
        try {
            // 1. 判断库存是否充足（如果有一本图书库存不足，就购买失败）
            for (OrderItem orderItem : orderItemList) {
                String bookId = orderItem.getBookId();
                Integer number = orderItem.getNumber();
                QueryWrapper<Stock> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("book_id", bookId);
                queryWrapper.select("number");
                Stock one = stockService.getOne(queryWrapper);
                UpdateWrapper<Stock> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("book_id", bookId);
                updateWrapper.set("number", one.getNumber() - number);
                stockService.update(updateWrapper);
            }
        } catch (Exception e) {
            log.info("库存不足:{}", e.getMessage());
            // 2. 如果不足 失败
            // 2.1 向rocketMQ发送一笔消息
            rocketMQTemplate.asyncSend("Order:error", JSONArray.toJSONString(rocketMQOrder), new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    log.info("消息sendResult：{}", sendResult);
                }

                @Override
                public void onException(Throwable throwable) {
                    log.info("消息sendResult：{}", throwable.getMessage());
                }
            });
            // 2.2 回滚当前消息
            return RocketMQLocalTransactionState.ROLLBACK;
        }

        // 3. 如果充足 成功
        log.info("库存充足");
        return RocketMQLocalTransactionState.COMMIT;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        return null;
    }
}
